<?php

namespace app\api\service\creative;

use app\api\model\creative\CreativeItem;
use app\api\model\creative\CreativeList;
use app\api\model\creative\CreativeRecords;
use app\api\model\creative\CreativeText;
use app\api\model\creative\CreativeVideos;
use app\api\model\creative\CreativeVideosGroup;
use app\api\service\token\LoginToken;
use app\lib\exception\creative\CreativeException;
use think\Db;
use think\Exception;

class EventService
{
    private static $instance;

    public static function getInstance(): EventService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取用户record列表
     */
    public function getRecords($params)
    {
        $pageSize = $params['pageSize']??50;
        $user_id = LoginToken::getInstance()->getCurrentUid();
        $result = CreativeRecords::where("user_id",$user_id)->paginate($pageSize);
        if ($result->isEmpty()){
            return "无数据";
        }else{
            return $result;
        }
    }

    /**
     * 获取要创作的任务
     */
    public function getCreative()
    {
        $ids = [];
        $list = CreativeList::where("status",1)->limit(0,3)->select();
        foreach ($list as $key => $value) {
            $ids[$key] = $value["id"];
        }
        $items = CreativeList::alias('l')
            ->field("l.id,t.duration,v.url,t.text")
            ->join("creative_item i", "l.id = i.list_id")
            ->join("creative_videos v", "v.id = i.video_id")
            ->join("creative_text t", "t.id = i.text_id")
            ->where("l.id", "in", $ids)
            ->select();
        foreach ($list as &$value) {
            $it = [];
            foreach ($items as $val) {
                if ($value["id"] == $val["id"]) {
                    $it[] = [
                        "text" => $val["text"],
                        "url" => $val["url"],
                        "duration" => $val["duration"],
                    ];
                }
            }
            $value["items"] = $it;
        }
        if ($list->isEmpty()){
            throw new CreativeException(['msg' => '无数据','error_code' => 400]);
        }else{
            CreativeList::where("id", "in", $ids)->update(["status"=>2]);
            return $list;
        }
    }

    /**
     * 获取文案列表
     */
    public function getTextList($params)
    {
        $result = CreativeText::where("record_id",$params['record_id'])->select();
        if ($result->isEmpty()){
            return "无数据";
        }else{
            return $result;
        }
    }

    /**
     * @param $params
     * 修改文案
     */
    public function modifyText($params)
    {
        $result = [];
        $user_id = LoginToken::getInstance()->getCurrentUid();
        $res = CreativeRecords::alias('r')->join('creative_text t','r.id = t.record_id')
            ->where("t.record_id", $params['record_id'])
            ->where("r.user_id", $user_id)
            ->where("t.id", $params['id'])
            ->findOrEmpty();

        DB::startTrans();
        try {
            if ($res->isEmpty()) {
                return "无数据";
            } else {
                $result = CreativeText::update($params);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $result;
    }



    /**
     * 新增视频分组
     */
    public function addGroup($params)
    {
        $group = [];
        $code = 0;
        $groups = CreativeVideosGroup::field("*");
        $user_id = LoginToken::getInstance()->getCurrentUid();
        $params['user_id'] = $user_id;
        $info = $groups->where($params)->findOrEmpty();
        DB::startTrans();
        try {
            if ($info->isEmpty()) {
                $group = CreativeVideosGroup::create($params, true);
                if (!$group) {
                    $code = 20001;
                }
            } else {
                $code = 20002;
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        if ($code == 20001) {
            throw new CreativeException(['msg' => '视频分组新增失败','error_code' => $code]);
        } else if ($code == 20002) {
            throw new CreativeException(['msg' => '视频分组已存在','error_code' => $code]);
        }
        return $group;
    }

    /**
     * 获取视频分组
     */
    public function getGroup()
    {
        $user_id = LoginToken::getInstance()->getCurrentUid();
        $result = CreativeVideosGroup::where("user_id",$user_id)->select();
        if ($result->isEmpty()){
            return "无数据";
        }else{
            return $result;
        }
    }

    public function getVideos($params)
    {
        $user_id = LoginToken::getInstance()->getCurrentUid();
        $query = CreativeVideosGroup::where("user_id",$user_id);
        if(!empty($params['groupname'])){
            $query->where('groupname',"like","%".$params['groupname']."%");
        }
        $group = $query->select();
        if ($group->isEmpty()){
            return "无数据";
        }else{
            $ids = [];
            foreach ($group as $key => $val) {
                $ids[$key] = $val["id"];
            }
            $videos = CreativeVideos::where('group_id','in', $ids)->select();
            foreach ($group as &$value) {
                $video = [];
                foreach ($videos as $val) {
                    if ($value['id'] == $val['group_id']) {
                        $video[] = [
                            "id" => $val[ "id"],
                            "filename" => $val[ "filename"],
                            "duration" => $val[ "duration"],
                            "url" => $val[ "url"],
                        ];
                    }
                }
                $value['videos'] = $video;
            }
            return $group;
        }
    }

    /**
     * 上传视频
     */
    public function uploadVideo($params){
        DB::startTrans();
        try {
            #写入数据库
            $data = [
                "group_id" => $params["group_id"],
                "filename" => $params["filename"],
                "duration" => $params["duration"],
                "url"=>$params["url"]
            ];

            CreativeVideos::create($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new CreativeException([
                'msg' => '上传失败',
                'error_code' => 20002
            ]);
        }
    }

    /**
     * 创建任务
     */
    public function createEvent($params)
    {

        $result = [];
        $user_id = LoginToken::getInstance()->getCurrentUid();
        $list = [
            "record_id" => $params["record_id"],
            "title" => $params["title"],
            "user_id" => $user_id
        ];
        $info = CreativeList::where($list)->findOrEmpty();
        $code = '';
        DB::startTrans();
        try {
            if ($info->isEmpty()) {
                $list["status"] = 1;
                $list_id = $info->create($list, true);
                $ids = [];
                foreach ($params["item"] as $key => $val) {
                    $ids[$key] = $val["text_id"];
                }

                $text = CreativeText::where('id','in', $ids)->select();
                $add = [];
                foreach ($params["item"] as $value) {
                    foreach ($text as $val) {
                        if ($value["text_id"] == $val["id"]) {
                            $add[] = [
                                "text_id" => $value["text_id"],
                                "list_id" => $list_id["id"],
                                "video_id" => $value["video_id"],
                                "duration" => $val["duration"]
                            ];
                        }
                    }
                }

                $result = CreativeItem::insertAll($add);

            } else {
                $code = 20002;
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        if ($code === 20001) {
            throw new CreativeException(['msg' => '任务新增失败','error_code' => 20001]);
        } else if ($code === 20002) {
            throw new CreativeException(['msg' => '任务重复','error_code' => 20002]);
        }
        return $result;
    }

    /**
     * 获取未翻译的视频，并更新状态为翻译中
     */
    public function getList()
    {
        $result = [];
        DB::startTrans();
        try {
            $record = CreativeRecords::where("status", '=', 1)->limit(0, 10)->select();
            if($record){
                $ids = [];
                foreach ($record as $item){
                    $result[] = $item;
                    $ids[] = $item['id'];
                }
                if (!empty($ids)) {
                    CreativeRecords::whereIn('id',$ids)->update([
                        'status' => 2,
                        'get_time' => date("Y-m-d H:i:s"),
                        'update_time' => date("Y-m-d H:i:s")
                    ]);
                }
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $result;
    }

    /**
     * 创意入库
     */
    public function setCreative($params)
    {
        $result = [];
        $code = 0;
        $user_id = LoginToken::getInstance()->getCurrentUid();
        $param = [
            "title" => $params["videoName"],
            "user_id" => $user_id
        ];
        $info = CreativeRecords::where($param)->findOrEmpty();
        DB::startTrans();
        try {
            if ($info->isEmpty()) {
                #写入数据库
                $data = [
                    "title" => $params["videoName"],
                    "status" => 1,
                    "video_url" => $params["link"],
                    "author"=>$params["authorName"],
                    "play_count"=>$params["views"],
                    "sale_count"=>$params["sales"],
                    "deal_count"=>$params["orders"],
                    "digg_count"=>$params["likes"],
                    "product_name"=>$params["productsName"],
                    "create_time"=>$params["time"],
                    "time"=>$params["videoTime"],
                    "user_id"=>$user_id
                ];
                $result = CreativeRecords::create($data);
            } else {
                $code = 20002;
            }

            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            $code = 20001;
        }
       if ($code === 20001) {
           throw new CreativeException(['msg' => '创意新增失败','error_code' => 20001]);
       } else if ($code === 20002) {
           throw new CreativeException(['msg' => '创意重复','error_code' => 20002]);
       }
       return $result;
    }

    /**
     * 文案入库（单条）
     */
    public function setText($params)
    {
        $result = [];
        Db::startTrans();
        try {
            $data = [
                "record_id"=>$params["record_id"],
                "text"=>$params["Text"],
                "begin_time"=>$params["BeginTime"],
                "end_time"=>$params["EndTime"],
            ];
            $event = CreativeText::where("record_id",$params["record_id"])
                ->where("text",$params["Text"])
                ->where("begin_time",$params["BeginTime"])
                ->where("end_time",$params["EndTime"])
                ->findOrEmpty();

            if ($event->isEmpty()){
                $data["duration"] = number_format(($data["end_time"] - $data["begin_time"])/1000, 2);
                $result = CreativeText::create($data, true);
            } else {
                throw new Exception( '数据重复');
            }

            DB::commit();

        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new CreativeException([
                'msg' => '导入失败',
                'error_code' => 20002
            ]);
        }
        return "RecordId:".$params["record_id"].".Id:".$result["id"]."已入库完成";
    }

    /**
     * 更新record状态
     */
    public function updateStatus($params)
    {
        Db::startTrans();
        try {
            $result = CreativeRecords::where("id",$params["record_id"])->update(["status"=>$params["status"]]);
            // 提交事务
            Db::commit();
        } catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new CreativeException([
                'msg' => '更新失败',
                'error_code' => 20003
            ]);
        }
        return $result;
    }

    /**
     * @param $params
     * 提交制作完成的任务
     */
    public function saveFile($params)
    {
        Db::startTrans();
        try {
            $result = CreativeList::where("id",$params["list_id"])
                ->update([
                    "video" => $params["video"],
                    "fm_url" => $params["fm"],
                    "status" => 3
                ]);
            // 提交事务
            Db::commit();
        } catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new CreativeException([
                'msg' => '更新失败',
                'error_code' => 20003
            ]);
        }
        return $result;
    }

    /**
     * 获取任务列表
     */
    public function getEvents($params)
    {
        $pageSize = $params['pageSize']??50;
        $user_id = LoginToken::getInstance()->getCurrentUid();
        $result = CreativeList::where("user_id",$user_id)->order("id", "desc")->paginate($pageSize);
        if ($result->isEmpty()){
            return "无数据";
        }else{
            return $result;
        }
    }
}
